import { Injectable } from "@nestjs/common"
import { UserEntity } from "./user.entity"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import { getCurrentDate } from "../../utils/getCurrentDate"
import { calculateHash } from "../../utils/hash"

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userEntity: Repository<UserEntity>
  ) {}
  /**
   *  User register
   * @param session
   * @param body
   * @param res
   */
  async register(body: any, res: any, session: any) {
    try {
      const { email, password, captcha } = body
      // 1.Determine if captcha is correct
      if (captcha?.toLowerCase() !== session?.captcha?.toLowerCase()) {
        res.json({
          status: "error",
          message: "验证码错误！"
        })
        return
      }
      // 2. Determine if account is duplicate
      const result = await this.userEntity.find({
        where: {
          email: email
        }
      })
      if (result.length !== 0) {
        res.json({ status: "error", message: "用户注册失败，邮箱已存在！" })
        return
      }
      // 3.Set self increasing id
      const { maxId } = await this.userEntity
        .createQueryBuilder("user")
        .withDeleted()
        .select("MAX(user.id)", "maxId")
        .getRawOne()
      const id = maxId === null ? 2002052700 : parseInt(maxId) + 1
      // 4.Execute add
      await this.userEntity.save({
        id,
        email,
        password: calculateHash(password),
        status: 1,
        create_date: getCurrentDate()
      })
      // 5.Return information
      res.json({
        status: "success",
        message: "用户注册成功！"
      })
    } catch (err) {
      console.log(err)
      res.json({
        status: "error",
        message: "服务器内部错误，请稍后再试！"
      })
    }
  }

  /**
   *  User login
   * @param body
   * @param res
   * @param session
   */
  async login(body: any, res: any, session: any) {
    try {
      const { email, password, captcha, rememberAccount } = body
      // 1.Determine if captcha is correct
      if (captcha?.toLowerCase() !== session?.captcha?.toLowerCase()) {
        res.status(200).json({
          status: "error",
          message: "验证码错误！"
        })
        return
      }
      // 2.Determine if account and password are correct
      const accountData = await this.userEntity.findOne({
        where: [
          {
            email,
            password: calculateHash(password)
          }
        ]
      })
      if (!accountData) {
        res.json({
          status: "error",
          message: "账号或密码错误！"
        })
        return
      }
      // 3.Open session
      session.cookie.maxAge = rememberAccount === "true" ? 604800000 : 7200000
      session.info = {
        character: "user",
        uid: accountData.id
      }
      // 4.Return information
      res.json({
        status: "success",
        message: "登录成功！"
      })
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }

  /**
   * User logout
   * @param res
   */
  async logout(res: any) {
    res.json("哈哈")
  }

  /**
   * Modify password
   * @param res
   */
  async update(res: any) {
    res.json("哈哈")
  }

  /**
   * 软删除用户
   * @param res
   */
  async delete(res: any) {
    res.json("哈哈")
  }

  /**
   * 删除用户
   * @param res
   */
  async remove(res: any) {
    res.json("哈哈")
  }

  /**
   * 获取所有用户信息
   * @param res
   */
  async getAll(res: any) {
    const data = await this.userEntity.find()
    res.json(data)
  }

  /**
   * 更新用户状态
   * @param res
   */
  async updateStatus(res: any) {
    res.json("哈哈")
  }

  /**
   * 获取用户数量
   * @param res
   */
  public async count(res: any): Promise<void> {
    try {
      const result = await this.userEntity.count()
      res.json(result)
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * Reset password
   * @param body
   * @param res
   * @param session
   */
  public async reset(body: any, res: any, session: any): Promise<void> {
    try {
      const { email, captcha, password } = body
      if (captcha === session.emailCaptcha) {
        await this.userEntity.update(
          { email },
          { password: calculateHash(password) }
        )
        res.json({ status: "success", message: "密码重置成功！" })
      } else {
        res.json({ status: "error", message: "验证码错误！" })
      }
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }
}
